/**
 * api/repairs
 */

const defaultToInteger = require('../../../utils/default-to-integer');
const sortQB = require('../../../utils/sort-qb')();
const md5 = require('../../../utils/md5');


module.exports = function(app) {
    const router = app.router;
    const Repair = app.models.Repair;
    const User = app.models.User;
    const RepairGood = app.models.RepairGood;
    const Batch = app.models.Batch;
    const Good = app.models.Good;

    /**
     * @apiVersion 1.0.0
     * @apiGroup Repair
     * @api {get} /repairs 获取角色列表
     * @apiParam {Number} status=ONLINE 上架状态 `0:OFFLINE, 1:ONLINE, 2:DEBUG`
     * @apiParam {Number} locate=home 角色位置 `home, post, repair, home_repair: 首页横幅`
     * @apiParam {Number} type=image 角色类型 `image, video`
     * @apiParam {Number} since 指定时间，单位秒
     * @apiParam {Number} page_size=20 分页大小
     * @apiParam {Number} page_num=1 页码
     * @apiParam {String} sort=priority-desc 排序，支持 `id-desc, id-asc, priority-desc`
     *
     * @apiParam {Number} status=1 `0:OFFLINE, 1:ONLINE, 2:DEBUG` 上架状态
     * @apiParam {Number} title 标题
     * @apiParam {String} locate 角色位置
     * @apiParam {String} scope 角色范围
     * @apiParam {String} scope_info 角色范围配置
     * @apiParam {String} type 角色类型 ``
     * @apiParam {String} asset_url 资源 URL
     * @apiParam {Number} width 宽
     * @apiParam {Number} height 高
     * @apiParam {Number} duration 角色时长，单位毫秒
     * @apiParam {String} url 跳转URL `如果为空则不跳转，其余按 H5内 `openPage.url` 和 全局规则`
     * @apiParam {Number} priority 排序优先级
     * @apiParam {Number} start_time 开始时间，单位秒
     * @apiParam {Number} end_time 结束时间，单位秒
     *
     * @apiSuccess {Number} status 上架状态
     * @apiSuccess {String} locate 角色位置 `home: repair: recommed: 推荐位`
     * @apiSuccess {String} scope 角色范围
     * @apiSuccess {String} scope_info 角色范围配置
     * @apiSuccess {String} type 角色类型
     * @apiSuccess {String} asset_url 资源 URL
     * @apiSuccess {Number} width 宽
     * @apiSuccess {Number} height 高
     * @apiSuccess {Number} duration 角色时长，单位毫秒
     * @apiSuccess {String} url 跳转 URL `如果为空则不跳转，其余按 H5内 `openPage.url` 和 全局规则`
     ** @apiSuccess {Number} params 请求参数
     * @apiSuccess {Number} priority 排序优先级
     * @apiSuccess {Number} start_time 开始时间，单位秒
     * @apiSuccess {Number} end_time 结束时间，单位秒
     *
     * @apiSampleRequest
     */
    router.get('/repairs', function *() {
        const query = this.query;

        // @TODO: 支持 scpoe 查询
        const repairs = yield Repair.query(qb => {
            qb.where('deleted', Repair.NOT_DELETED);

            if(query.status && query.status !== 'all') {
                qb.where('status', query.status);
            }
            if(query.type && query.type !== 'all') {
                qb.where('type', query.type);
            }

            if(query.creator_id && +query.creator_id > 0) {
                qb.where('creator_id', query.creator_id);
            }
            if(query.department_id && +query.department_id > 0) {
                qb.where('department_id', query.department_id);
            }
            if(query.statistic_type) {
                qb.count('id as count');
                qb.select('id', 'department_id', 'repairer_id', 'checker_id', 'creator_id', 'allocator_id', 'status');
                if(query.statistic_type === '部门维修统计') {
                    qb.groupBy('department_id', 'status');
                }

                if(query.statistic_type === '工程师工单统计') {
                    qb.groupBy('repairer_id', 'status');
                }
            }
            // sort
            qb.orderBy('id', 'DESC');
        })
        .fetchItems({
            page_size: query.page_size,
            page_num: query.page_num
        }, {
            withRelated: ['creator', 'allocator', 'checker', 'department', 'repairer', 'goods.batch.good']
        });

        this.body = repairs;
    });

    router.get('/repairs/:id', function *() {
        this.body = yield Repair.where({
            id: this.params.id
        })
        .fetch({
            require: true
        });
    });

    /**
     * @apiVersion 1.0.0
     * @apiGroup Repair
     * @api {post} /repairs 新建角色
     *
     * @apiParam {Number} status 上架状态
     * @apiParam {String} locate 角色位置
     * @apiParam {String} scope 角色范围
     * @apiParam {String} scope_info 角色范围配置
     * @apiParam {String} type 角色类型
     * @apiParam {String} asset_url 资源 URL
     * @apiParam {Number} width 宽
     * @apiParam {Number} height 高
     * @apiParam {Number} duration 角色时长，单位毫秒
     * @apiParam {String} url 跳转 URL，如果为空则不跳转，其余按 H5内 `openPage.url` 规则
     * @apiParam {Number} priority 排序优先级
     * @apiParam {Number} start_time 开始时间，单位秒
     * @apiParam {Number} end_time 结束时间，单位秒
     */
    router.post('/repairs', function *() {
        let body = this.request.body;

        body.creator_id = this.headers['x-user'];

        const user = yield User.where({
            id: body.creator_id
        })
        .fetch();

        body.department_id = user.get('department_id');

        let repair = Repair.safeForge(body);

        this.body = yield repair.save();
    });

    /**
     * @apiVersion 1.0.0
     * @apiGroup Repair
     * @api {put} /repairs/:id 修改角色
     *
     * @apiParam {Number} status 上架状态
     * @apiParam {String} locate 角色位置
     * @apiParam {String} scope 角色范围
     * @apiParam {String} scope_info 角色范围配置
     * @apiParam {String} type 角色类型 ``
     * @apiParam {String} recommend_type `home_recommend: 首页顶部推荐, feature_recommend: 特性（标签）推荐, templet_recommend 模板库推荐`
     * @apiParam {String} asset_url 资源 URL
     * @apiParam {Number} width 宽
     * @apiParam {Number} height 高
     * @apiParam {Number} duration 角色时长，单位毫秒
     * @apiParam {String} url 跳转URL `如果为空则不跳转，其余按 H5内 `openPage.url` 和 全局规则`
     * @apiParam {Number} priority 排序优先级
     * @apiParam {Number} start_time 开始时间，单位秒
     * @apiParam {Number} end_time 结束时间，单位秒
     *
     * @apiSuccess {Number} status 上架状态
     * @apiSuccess {String} locate 角色位置 `home: repair: recommed: 推荐位`
     * @apiSuccess {String} scope 角色范围
     * @apiSuccess {String} scope_info 角色范围配置
     * @apiSuccess {String} type 角色类型
     * @apiSuccess {String} asset_url 资源 URL
     * @apiSuccess {Number} width 宽
     * @apiSuccess {Number} height 高
     * @apiSuccess {Number} duration 角色时长，单位毫秒
     * @apiSuccess {String} url 跳转 URL `如果为空则不跳转，其余按 H5内 `openPage.url` 和 全局规则`
     * @apiSuccess {Number} priority 排序优先级
     * @apiSuccess {Number} start_time 开始时间，单位秒
     * @apiSuccess {Number} end_time 结束时间，单位秒
     */
    router.put('/repairs/:id', function *() {
        const body = this.request.body;
        let repair = yield Repair.where({
            id: this.params.id
        })
        .fetch({
            require: true
        });

        if(body.goods) {
            for(let i = 0; i < body.goods.length; i++) {
                const good = body.goods[i];

                const batches = yield Batch.query(qb => {
                    qb.where('deleted', Batch.NOT_DELETED);
                    qb.where('good_id', good.id);
                    qb.where('stock', '>', 0);
                    qb.where('stock', '!=', 'used_stock');
                    qb.orderBy('id', 'asc');
                })
                .fetchAll();
                if(batches.length > 0) {
                    let stock = good.stock;
                    const repairGood = [];
                    const goodModel = yield Good.where({
                        id: good.id
                    })
                    .fetch();

                    if(stock > goodModel.get('stock')) {
                        this.throw(400, `${good.name}库存不足, 当前库存${goodModel.get('stock')}`);
                    }
                    goodModel.set('stock', goodModel.get('stock') - stock);

                    for(let j = 0; j < batches.models.length; j++) {
                        const batch = batches.models[j];
                        if(stock > 0 && batch.get('stock') - batch.get('used_stock') > 0) {
                            if(batch.get('stock') - batch.get('used_stock') >= stock) {
                                repairGood.push({
                                    good_id: good.id,
                                    stock: stock,
                                    repair_id: this.params.id,
                                    batch_id: batch.get('id'),
                                    price: batch.get('price')
                                });

                                batch.set('used_stock', stock + batch.get('used_stock'));
                                yield batch.save();
                                stock = 0;
                            }
                            else {
                                batch.set('used_stock', batch.get('stock'));

                                stock = stock - batch.get('stock');

                                repairGood.push({
                                    good_id: good.id,
                                    repair_id: this.params.id,
                                    stock: batch.get('stock'),
                                    batch_id: batch.get('id'),
                                    price: batch.get('price')
                                });

                                yield batch.save();
                            }
                        }
                    }

                    yield goodModel.save();

                    const rgs = RepairGood.Collection.forge(repairGood);

                    yield rgs.invokeMap('save');

                    this.body = body;

                    return;
                }
                else {
                    this.throw(400, `${good.name}暂无库存`);
                }
            }
        }
        // if(repair.get('status') === Repair.PENDING) {
        //     body.status = Repair.ALLOCATED;
        //     body.allocator_id = this.headers['x-user'];
        // }

        // if(repair.get('status') === Repair.ALLOCATED) {
        //     body.status = Repair.REPAIRED;
        // }

        // if(repair.get('status') === Repair.REPAIRED) {
        //     body.status = Repair.COMPLETED;
        //     body.checker_id = this.headers['x-user'];
        // }

        delete body.creator;
        delete body.checker;
        delete body.allocator;
        delete body.repairer;
        delete body.department;

        delete body.goods;

        repair.safeSet(body);

        yield repair.save();

        this.body = repair;
    });

    /**
     * @apiVersion 1.0.0
     * @apiGroup Repair
     * @api {delete} /repairs/:id 删除角色
     */
    router.delete('/repairs/:id', function *() {
        let repair = yield Repair.where({
            id: this.params.id
        })
        .fetch({
            require: true
        });

        repair.set('deleted', Repair.DELETED);

        yield repair.save();

        this.body = this.params;
    });

    router.get('/repairs/goods', function * () {
        const query = this.query;
        const goods = RepairGood.query(qb => {
            qb.where('repair_id', query.repair_id);
            qb.groupBy('good_id');
            qb.sum('stock');
        })
        .fetchItems({
            page_size: 100
        });

        this.body = query
    });
};
